package com.yunchang.springboot.scheduled.mwsfinance;

import com.yunchang.springboot.base.BaseService;
import com.yunchang.springboot.mapper.mwsfinance.FInventoryDailyMapper;
import com.yunchang.springboot.mapper.mwsfinance.FInventoryDetailsMapper;
import com.yunchang.springboot.models.mwsfinance.FInventoryDaily;
import com.yunchang.springboot.models.mwsfinance.FInventoryDetails;
import com.yunchang.springboot.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 库存
 *
 * @author Administrator
 */
@Component
@Configuration
@Service
@Slf4j
@EnableScheduling
public class FInventoryDailyScheduled extends BaseService {

    private String REASON = null;

    /**
     * 对采用哪一种运算方式进行判断的warehouse值
     */
    private List<String> WAREHOUSE_VALUES = Arrays.asList("140203", "140204", "140205", "140210", "140211");

    /**
     * 对于relatedId的warehouse判断值
     */
    private List<String> WAREHOUSE_VALUES_RELATED = Arrays.asList("140201", "140601");

    /**
     * 出入库明细数据
     */
    FInventoryDetailsMapper fInventoryDetailsMapper;

    @Autowired
    public void setFInventoryDetailsMapper(FInventoryDetailsMapper fInventoryDetailsMapper) {
        this.fInventoryDetailsMapper = fInventoryDetailsMapper;
    }

    /**
     * 库存
     */
    FInventoryDailyMapper fInventoryDailyMapper;

    @Autowired
    public void setFInventoryDailyMapper(FInventoryDailyMapper fInventoryDailyMapper) {
        this.fInventoryDailyMapper = fInventoryDailyMapper;
    }

    public void getInventoryDaily(String date) {
        List<FInventoryDetails> fInventoryDetailsList = fInventoryDetailsMapper.selectByIsInventoryDailyAndDate(1, date);
        if (null != fInventoryDetailsList && !fInventoryDetailsList.isEmpty()) {
            for (FInventoryDetails fInventoryDetails : fInventoryDetailsList) {
                isWareHouse(fInventoryDetails, date);
                fInventoryDetails.setIsInventoryDaily(2);
            }
            try {
                // 更新出入库明细中的是否生成库存数据状态
                fInventoryDetailsMapper.updateIsInventoryDailyByFInventoryDetailsList(fInventoryDetailsList);
                log.info("出入库明细数据已更新" + date);
            } catch (Exception e) {
                log.error("出入库明细数据更新时出现错误，出入库明细数据生成库存数据" + e);
                throw new RuntimeException("出入库明细数据更新时出现错误，出入库明细数据生成库存数据");
            }
        } else {
            log.info("获取的出入库明细数据为空，时间为：" + DateUtil.getTodayDate("yyyy-MM-dd HH:mm:ss"));
        }
    }

    /**
     * 根据warehouse判断是否使用哪些参数获取对应的库存数据
     * @param fInventoryDetails
     * @param date
     */
    public void isWareHouse(FInventoryDetails fInventoryDetails, String date) {
        String warehouse = fInventoryDetails.getWarehouse();
        String country = fInventoryDetails.getCountry();
        String sku = fInventoryDetails.getSku();
        String relatedId = fInventoryDetails.getRelatedOrderId();
        if (WAREHOUSE_VALUES_RELATED.contains(warehouse)) {
            if (!StringUtils.isEmpty(fInventoryDetails.getRelatedOriginalOrderId())) {
                relatedId = fInventoryDetails.getRelatedOriginalOrderId();
            } else {
                relatedId = fInventoryDetails.getRelatedOrderId();
            }
        }
        String stockSku = fInventoryDetails.getStockSku();
        String sellerId = fInventoryDetails.getSellerId();
        if (StringUtils.isEmpty(warehouse)) {
            return;
        }
        if (warehouse.equals("140601")) {
            FInventoryDaily fInventoryDaily = fInventoryDailyMapper.selectBySellerIdAndCountryAndSkuAndWarehouseAndRelatedIdAndDate(sellerId, country, sku, warehouse, relatedId, date);
            inventoryDispose(fInventoryDaily, fInventoryDetails, date);
        }
        if (warehouse.startsWith("1406") && !warehouse.equals("140601")) {
            FInventoryDaily fInventoryDaily = fInventoryDailyMapper.selectBySellerIdAndCountryAndSkuAndWarehouseAndDate(sellerId, country, sku, warehouse, date);
            inventoryDispose(fInventoryDaily, fInventoryDetails, date);
        }
        if (WAREHOUSE_VALUES.contains(warehouse)) {
            FInventoryDaily fInventoryDaily = fInventoryDailyMapper.selectBySellerIdAndCountryAndWarehouseAndRelatedIdAndDateAndStockSku(sellerId, country, warehouse, relatedId, stockSku, date);
            inventoryDispose(fInventoryDaily, fInventoryDetails, date);
        }
        if (!WAREHOUSE_VALUES.contains(warehouse) && warehouse.startsWith("1402")) {
            FInventoryDaily fInventoryDaily = fInventoryDailyMapper.selectBySellerIdAndCountryAndSkuAndWarehouseAndRelatedIdAndDate(sellerId, country, sku, warehouse, relatedId, date);
            inventoryDispose(fInventoryDaily, fInventoryDetails, date);
        }
    }

    /**
     * 库存处理
     * @param fInventoryDaily
     * @param fInventoryDetails
     */
    public void inventoryDispose(FInventoryDaily fInventoryDaily, FInventoryDetails fInventoryDetails, String date) {
        String warehouse = fInventoryDetails.getWarehouse();
        Integer quantity = fInventoryDetails.getQuantity();
        Double amount = fInventoryDetails.getAmount();
        Integer type = fInventoryDetails.getType();
        if (null != fInventoryDaily) {
            Integer inventoryQuantity = fInventoryDaily.getQuantity();
            Double inventoryAmount = fInventoryDaily.getAmount();
            Double updateInventoryAmount = 0.0;
            Integer updateInventoryQuantity = 0;
            if (null != inventoryAmount && null != inventoryQuantity && null != amount && null != quantity) {
                if (type == 1) {
                    updateInventoryQuantity = inventoryQuantity - quantity;
                    updateInventoryAmount = inventoryAmount - amount;
                }
                if (type == 2) {
                    updateInventoryQuantity = inventoryQuantity + quantity;
                    updateInventoryAmount = inventoryAmount + amount;
                }
            }
            fInventoryDaily.setQuantity(updateInventoryQuantity);
            fInventoryDaily.setAmount(updateInventoryAmount);
            fInventoryDaily.setDate(date);
            baseUpdate(fInventoryDaily);
        } else {
            FInventoryDaily fInventoryDailyInsert = new FInventoryDaily();
            fInventoryDailyInsert.setIsEndAdjustment(1);
            fInventoryDailyInsert.setSellerId(fInventoryDetails.getSellerId());
            fInventoryDailyInsert.setCountry(fInventoryDetails.getCountry());
            fInventoryDailyInsert.setSku(fInventoryDetails.getSku());
            fInventoryDailyInsert.setStockSku(fInventoryDetails.getStockSku());
            fInventoryDailyInsert.setFnsku(fInventoryDetails.getFnsku());
            fInventoryDailyInsert.setWarehouse(fInventoryDetails.getWarehouse());
            if (WAREHOUSE_VALUES_RELATED.contains(warehouse)) {
                if (!StringUtils.isEmpty(fInventoryDetails.getRelatedOriginalOrderId())) {
                    fInventoryDailyInsert.setRelatedId(fInventoryDetails.getRelatedOriginalOrderId());
                } else {
                    fInventoryDailyInsert.setRelatedId(fInventoryDetails.getRelatedOrderId());
                }
            }
            if(warehouse.startsWith("1402") && !warehouse.equals("140201")){
                fInventoryDailyInsert.setRelatedId(fInventoryDetails.getRelatedOrderId());
            }
            if (type == 1) {
                fInventoryDailyInsert.setQuantity(fInventoryDetails.getQuantity()*-1);
                fInventoryDailyInsert.setAmount(fInventoryDetails.getAmount()*-1);
            }
            if (type == 2) {
                fInventoryDailyInsert.setQuantity(fInventoryDetails.getQuantity());
                fInventoryDailyInsert.setAmount(fInventoryDetails.getAmount());
            }
            fInventoryDailyInsert.setCurrency(fInventoryDetails.getCurrency());
            fInventoryDailyInsert.setDate(date);
            fInventoryDailyInsert.setCreateTime(DateUtil.getTodayDate("yyyy-MM-dd HH:mm:ss"));
            fInventoryDailyInsert.setUpdateTime(DateUtil.getTodayDate("yyyy-MM-dd HH:mm:ss"));
            baseInsert(fInventoryDailyInsert, true);
        }
    }

    /**
     * 根据日期获取前一天的库存数据，并将其更改为新的日期插入数据库
     *
     * @param date
     */
    public void insertInventoryByDate(String date) {
        String maxDate = fInventoryDailyMapper.selectMaxDate();
        maxDate = maxDate.substring(0,10);
        if(maxDate.equals(date)){
            return;
        }
        // 获取前一天的数据
        String beforeDay = DateUtil.getBeforeDay(date);
        // 根据前一天的日期获取对应的数据
        List<FInventoryDaily> fInventoryDailyList = fInventoryDailyMapper.selectByDate(beforeDay);
        List<Object> fInventoryDailyInsertList = new ArrayList<>(fInventoryDailyList.size());
        for (FInventoryDaily fInventoryDaily : fInventoryDailyList) {
            fInventoryDaily.setDate(date);
            fInventoryDaily.setId(null);
            fInventoryDaily.setCreateTime(DateUtil.getTodayDate("yyyy-MM-dd HH:mm:ss"));
            fInventoryDaily.setUpdateTime(DateUtil.getTodayDate("yyyy-MM-dd HH:mm:ss"));
            fInventoryDaily.setIsEndAdjustment(1);
            fInventoryDailyInsertList.add(fInventoryDaily);
        }
        try {
            baseInsertList(fInventoryDailyInsertList);
            log.info("新一天的库存数据已添加，日期为：" + date);
        } catch (Exception e) {
            log.error("插入数据时出现错误，根据日期更新库存数据" + e);
            throw new RuntimeException("插入数据时出现错误，根据日期更新库存数据");
        }
    }

}
